package cn.wolfcode.wechat.service.impl;

import cn.wolfcode.wechat.domain.Account;
import cn.wolfcode.wechat.domain.Client;
import cn.wolfcode.wechat.domain.OrderBill;
import cn.wolfcode.wechat.mapper.OrderBillMapper;
import cn.wolfcode.wechat.query.OrderBillQueryObject;
import cn.wolfcode.wechat.service.IAccountService;
import cn.wolfcode.wechat.service.IClientService;
import cn.wolfcode.wechat.service.IOrderBillService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class OrderBillServiceImpl implements IOrderBillService {
    @Autowired
    private IAccountService accountService;
    @Autowired
    private OrderBillMapper orderBillMapper;
    @Autowired
    private IClientService clientService;

    @Override
    public int save(OrderBill bill) {
        return orderBillMapper.insert(bill);
    }

    @Override
    public int update(OrderBill bill) {
        return orderBillMapper.updateByPrimaryKey(bill);
    }

    @Override
    public OrderBill get(Long id) {
        return orderBillMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<OrderBill> listAll() {
        return orderBillMapper.selectAll();
    }


    @Override
    public PageInfo queryPage(OrderBillQueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        System.out.println("---------" + qo);
        List pageResult = orderBillMapper.queryPage(qo);
        return new PageInfo(pageResult);
    }

    @Override
    public void creatOrder(OrderBill orderBill) {
        Client client = clientService.selectByOpenid(orderBill.getOpenid());
        Account account = accountService.get(client.getId());
        if (account.getUsableAmount().compareTo(orderBill.getFee()) < 0){
            throw new RuntimeException("您的账户余额不足,请充值后再试");
        }
        this.save(orderBill);
    }


}
